package com.easy.activiti.controller;

import com.easy.activiti.ext.IActivitiCoreService;
import com.easy.activiti.util.AjaxResponse;
import com.easy.activiti.mapper.ActivitiMapper;
import com.easy.activiti.util.GlobalConfig;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.authentication.AnonymousAuthenticationToken;
import org.springframework.security.core.Authentication;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.SimpleGrantedAuthority;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.context.SecurityContextImpl;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import java.util.ArrayList;
import java.util.Collection;

@RestController
@RequestMapping("/activiti/user")
public class UserController {
    private static final Logger log = LoggerFactory.getLogger(UserController.class);

    @Autowired
    ActivitiMapper mapper;
    @Autowired
    private IActivitiCoreService activitiCoreService;

    private   boolean isLoggedIn() {
        Authentication authentication = SecurityContextHolder.getContext().getAuthentication();
        return authentication != null && authentication.isAuthenticated()
                && !(authentication instanceof AnonymousAuthenticationToken);
    }
    @GetMapping(value = "/getLoginUser")
    public AjaxResponse getLoginUser() {
        try {
            IActivitiCoreService.AuthConfigServer.User user = activitiCoreService.authConfigServer().loginUser();

            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.SUCCESS.getCode(),
                    GlobalConfig.ResponseCode.SUCCESS.getDesc(), activitiCoreService.authConfigServer().loginUser());
        } catch (Exception e) {
            e.printStackTrace();
            return AjaxResponse.AjaxData(GlobalConfig.ResponseCode.ERROR.getCode(),
                    "获取用户信息失败", e.toString());
        }
    }
    public void logInAs(IActivitiCoreService.AuthConfigServer.User user) {
        if (user == null) {
            throw new IllegalStateException("还未登陆，请先登录");
        }

        log.error(String.format("==============用户%s在线程%s,%s又登陆了===========",user.getUserName(),Thread.currentThread().getName(),Thread.currentThread().getId()));
//      request.getSession().getServletContext().getSessionCookieConfig().setName();
        SecurityContextHolder.setContext(new SecurityContextImpl(new Authentication() {
            @Override
            public Collection<? extends GrantedAuthority> getAuthorities() {
                Collection<GrantedAuthority> authorities = new ArrayList<>();
                for (String role : user.getRoles()) {
                    authorities.add(new SimpleGrantedAuthority(role));
                }
                return authorities;
            }

            @Override
            public Object getCredentials() {
                return null;
            }

            @Override
            public Object getDetails() {
                return user;
            }

            @Override
            public Object getPrincipal() {
                return user;
            }

            @Override
            public boolean isAuthenticated() {
                return true;
            }

            @Override
            public void setAuthenticated(boolean isAuthenticated) throws IllegalArgumentException {

            }

            @Override
            public String getName() {
                return user.getUserName();
            }
        }));
        org.activiti.engine.impl.identity.Authentication.setAuthenticatedUserId(user.getUserName());
    }
}
